﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


using Swaf;
using Swaf.BizObj;
using Swaf.BizRule;
using Swaf.Container;
using Swaf.Gui;

namespace Survey.Gui
{
    public class SurveyBizProc : Articles.Gui.ArticleManagementBizProc
    {
        protected string _formData = "formData";
        protected string _metaType = "-ArtForm";
        
        public SurveyBizProc(ActiveBizProc procState)
            : base(procState)
        {
            setupProcState();
            base.m_updateArtFormBizRule = "updateUserSurveyFormData";                
        }
        
        protected virtual void setupProcState()
        {
			if(Cmn.IsEmpty(m_procState.get("pid")))
				m_procState.put("pid", string.Format("Survey-{0}", ActiveCompany.get("shortName")));
            m_procState.put("entireTree", true);
            m_procState.put("includeSelf", true);
        }

        public override IBizObj CurrentBizObj
        {
            get
            {
                IBizObj survey = base.CurrentBizObj;

                if (survey!=null && (int)survey.get("minAnswer")==0)
                {
                    IResults rc = App.ruleMgr.execute("getSurveySettings",survey);
                    if (rc.ExceptionInfo == null)
                        return rc.CallResults as IBizObj;
                }
                return survey;
            }
        }
        protected override void setupRuleNames()
        {
            base.setupRuleNames();
            base.m_getBizObjListRule = "getCompanySurvey";
        }
        /// <summary>
        /// when creating a survey for a company, the survey should be prefix
        /// with Survey- (TODO: this can be automated by creating a default company survey 
        /// during new company creation)
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        protected override IBizObj setupNewBizObj(IBizObj obj)
        {
            obj.put("id", new Swaf.BGuid.Guid());
            obj.put("parentId", CurrentBizObj.get("id"));
            obj.put("baseTitle", "Survey Name");
            obj.put("metaType", _metaType);
            obj.put("counts.author.id", CurrentUser.get("id"));
            return obj;
        }

        public override void updateArtForm(object formData)
        {
            if (m_procState.get(_formData) != null && m_procState.get(_formData).ToString().Equals(formData.ToString()))
            {
                this.moveNext();
            }
            else
                if (!Cmn.IsEmpty(m_updateArtFormBizRule))
                {
                    IResults rc = App.ruleMgr.execute(m_updateArtFormBizRule, getUpdateArtFormBizRuleParams(formData));
                    if (rc.ExceptionInfo == null)
                    {
                        m_procState.put(_formData, formData);
                        this.moveNext();
                    }
                    else
                    {
                        if (rc.ExceptionInfo.Message.Contains("|"))
                        {
                            string[] ids = rc.ExceptionInfo.Message.Split('|');
                            FlexiMap m = new FlexiMap();
                            m.put("ValidationValue", ids[1]);
                            m_procState.BPC.Messenger.add(ids[0], m);
                        }
                        else
                        {
                            FlexiMap m = new FlexiMap();
                            m.put("ValidationValue", rc.ExceptionInfo.Message);
                            m_procState.BPC.Messenger.add("CriticalSystemError", m);
                        }
                    }
                }
            
        }

        public override void moveNext()
        {
            base.moveNext();
            calcUserFormData();
        }

        public override void movePrev()
        {
            base.movePrev();
            calcUserFormData();
            
        }
        protected void calcUserFormData()
        {
            if (CurrentBizObj != null)
            {
                IResults rc = App.ruleMgr.execute("getUserFormData", CurrentBizObj.get("id") as Swaf.BGuid.Guid);
                if (rc.ExceptionInfo == null)
                {
                    IBizObj bizobj = rc.CallResults as IBizObj;
                    if (bizobj != null)
                    {
                        m_procState.put(_formData, bizobj.get("formData"));
                        m_procState.put("pushFormData", true);
                    }
                }
                else
                {
                    FlexiMap m = new FlexiMap();
                    m.put("CriticalSystemError", rc.ExceptionInfo.Message);
                    m_procState.BPC.Messenger.add("CriticalSystemError", m);
                }
            }
        }
        public override void updateActionState()
        {
            base.updateActionState();
            if (m_retrievedBizObjList)
            {
                ((GenericAction)Actions["MoveNext"]).Availability = showControl("MoveNext");
                ((GenericAction)Actions["MovePrev"]).Availability = showControl("MovePrev");
                if (((GenericAction)Actions["MoveNext"]).Availability == ActionAvailability.none && LastQuestionOnSurvey)
                    ((GenericAction)Actions["UpdateArtForm"]).Availability = ActionAvailability.none;
            }
            
        }

        protected bool LastQuestionOnSurvey
        {
            get
            {
                int numElement = SourceBizObjs.numElements;
                if (SourceBizObjs != null && numElement > 1)
                    return CurrentBizObj.get("id").Equals(SourceBizObjs[numElement-1].get("id"));
                return false;
            }
        }

        protected bool FirstQuestionOnSurvey
        {
            get
            {
                if (SourceBizObjs != null && CurrentBizObj != null)
                {
                    if (CurrentBizObj.get("id").Equals(SourceBizObjs[0].get("id")))
                        return true;
                }
                return false;
            }
        }
        protected void addUserFormData(object formData)
        {
            if (App.sessionData.get(_formData) == null)
            {

            }
        }

        protected ActionAvailability showControl(string name)
        {
            if (name.Equals("MoveNext"))
            {
                if (CurrentBizObj != null && string.Compare((string)CurrentBizObj.get("metaType"), _metaType) == 0)
                    return ActionAvailability.none;
                else if (CurrentBizObj != null && string.Compare((string)CurrentBizObj.get("metaType"), _metaType) != 0 && LastQuestionOnSurvey)
                    return ActionAvailability.none;
                return ActionAvailability.enabled;

            }
            else if (name.Equals("MovePrev"))
            {
                if (SourceBizObjs != null && SourceBizObjs.numElements > 1)
                {
                    if (!CurrentBizObj.get("id").Equals(SourceBizObjs[0].get("id")))
                        return ActionAvailability.enabled;
                }
                return ActionAvailability.none;
            }
            else
                return ActionAvailability.none;
        }


       

       
    }
}
